﻿/**************************************************************
 *
 * 唯一标识：36bb593a-fc93-4a45-93f4-7c41318bd4bd
 * 命名空间：Sgr.UPMS.Application.Commands.Users
 * 创建时间：2023/8/27 11:34:55
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：重置密码命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.Domain.Entities;
using Sgr.Identity.Services;
using Sgr.UPMS.Domain.Organizations;
using Sgr.UPMS.Domain.Users;
using Sgr.Utilities;
using System.Reflection.Metadata;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Users
{
    /// <summary>
    /// 重置密码命令处理器
    /// </summary>
    public class ResetPasswordCommandHandle : IRequestHandler<ResetPasswordCommand, CommandResult<string>>
    {
        private readonly IUserRepository _userRepository;
        private readonly IPasswordHashService _passwordHashService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository">用户仓储</param>
        /// <param name="passwordHashService">密码哈希服务</param>
        public ResetPasswordCommandHandle(IUserRepository userRepository, IPasswordHashService passwordHashService)
        {
            _userRepository = userRepository;
            _passwordHashService = passwordHashService;
        }

        /// <summary>
        /// 处理重置密码命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<string>> Handle(ResetPasswordCommand request, CancellationToken cancellationToken)
        {
            // 查找用户实体
            var user = await _userRepository.GetAsync(request.UserId, cancellationToken);

            // 如果找不到用户，返回NotFound结果
            if (user == null)
                return CommandResult.NotFound<string>("用户不存在");

            if (user.State == Sgr.Domain.Entities.EntityStates.Deactivate)
                return CommandResult.Invalid<string>("用户已被禁用，无法重置密码");

            //  Constant.SUPER_ADMIN_ORG_ID 对应组织的用户不可以重置密码
            var ruleCheckResult = user.CanChangePassword();
            if (!ruleCheckResult.IsComply)
                return CommandResult.Invalid<string>(ruleCheckResult.Message);

            // 生成临时密码
            string tmpPassword = RandomHelper.GetRandomString(8, true, true, false, false);

            // 重置密码
            user.ChangePassword(_passwordHashService, tmpPassword);

            // 更新到仓储
            await _userRepository.UpdateAsync(user, cancellationToken);

            // 返回成功结果
            return CommandResult.Success<string>(tmpPassword, "重置成功");
        }
    }
}